<template>
  <div class="activities-shop">
    <!-- 筛选头部 -->
    <div class="search-box">
      <el-form ref="adSearchForm" :inline="true" :model="adSearchInfo" class="search-form">
        <el-form-item label="广告名称：">
          <el-input v-model="adSearchInfo.name" size="medium" placeholder="请输入广告名称" />
        </el-form-item>
        <el-form-item label="活动状态：">
          <el-select v-model="adSearchInfo.state" size="medium" placeholder="请输入广告状态">
            <el-option label="已开启" value="00400001" />
            <el-option label="已停用" value="00400002" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="medium" @click="toSearch">查询</el-button>
          <el-button size="medium" @click="resetSearchInfo">重 置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 广告列表 -->
    <div class="ad-list-wrapper">
      <div v-loading="loading" class="ad-list">
        <div class="ad-list-func">
          <div>
            <el-checkbox v-model="checkedAll" @change="checkAll">全部</el-checkbox>
            <el-button class="button" icon="el-icon-delete" size="small" @click="deleteMany">批量删除</el-button>
            <p class="selected-num">已选择 <span>{{ checkedCount }}</span> 项</p>
            <el-button type="text" @click="clearAll">清空</el-button>
          </div>
          <router-link :to="{name: 'AdAdd'}"><el-button type="primary" icon="el-icon-plus" size="small">添加广告</el-button></router-link>
        </div>
        <div v-if="adList.length === 0" class="none">
          你还没有添加广告～
        </div>
        <table v-else width="100%" align="left" border="0" cellpadding="0" cellspacing="0">
          <thead>
            <tr><th class="checkbox" /><th class="img">广告图片</th><th>广告名称</th><th class="type">链接类型</th><th>创建时间</th><th class="state">状态</th><th class="func">操作</th></tr>
          </thead>
          <tbody>
            <tr v-for="(ad, index) in adList" :key="index" class="ad-list-item">
              <td class="check"><el-checkbox v-model="ad.selected" @change="checkItem" /></td>
              <td><el-image style="width: 300px; height: 100px" :src="qnPath(ad.imagePc) + '?imageView2/1/w/300/h/100'" fit="fit" /></td>
              <td>{{ ad.name }}</td>
              <td>{{ ad.linkType === '0' ? '商品' : ad.linkType === '2' ? '图片' : '活动' }}</td>
              <td><p>{{ new Date(ad.createDate) | getDate('-') }}&nbsp;{{ new Date(ad.createDate) | getTime }}</p></td>
              <td><el-switch v-model="ad.status" active-value="00400001" inactive-value="00400002" @change="changeStatus(ad)" />&nbsp;<span v-if="ad.status">已启用</span><span v-else class="disabled">已停用</span></td>
              <td>
                <router-link :to="{name: 'AdDetail', params: { id: ad.id }}"><el-button type="text">查看</el-button></router-link>
                <el-divider direction="vertical" />
                <router-link :to="{name: 'AdEdit', params: { id: ad.id }}"><el-button type="text">编辑</el-button></router-link>
                <el-divider direction="vertical" />
                <el-button type="text" @click="handleDelete(ad.id)">删除</el-button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          :current-page.sync="currentPage"
          :page-size="pageSize"
          layout="prev, pager, next, sizes, jumper"
          :total="adCount"
          :hide-on-single-page="true"
          :page-sizes="[10, 20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>
</template>
<script>
import { getList, delAndStart } from '@/api/ad';
import { mapGetters } from 'vuex';
export default {
  name: 'AdShop',
  data() {
    return {
      loading: false,
      adSearchInfo: {
        name: '',
        state: ''
      },
      adList: [],
      checkedAll: false,
      checkedCount: 0,

      // 分页
      currentPage: 1,
      pageSize: 5,
      adCount: 1
    };
  },
  computed: {
    ...mapGetters(['shopInfo'])
  },
  watch: {
    checkedCount(value) {
      this.checkedAll = value === this.adList.length;
    }
  },
  mounted() {
    this.getList();
  },
  activated() {
    if (this.$route.query.reload) this.getList();
  },
  methods: {
    getList(
      shopId = this.shopInfo.id,
      pageNo = this.currentPage,
      pageSize = this.pageSize,
      searchName = this.adSearchInfo.name,
      status = this.adSearchInfo.state,
    ) {
      this.loading = true;
      new Promise((resolve, reject) => {
        getList({ shopId, pageNo, pageSize, searchName, status }).then(res => {
          this.loading = false;
          const list = res.data.Advertisement;
          list.forEach(ad => {
            ad.selected = false;
            // ad.status = ad.status === '00400001';
          });
          this.adList = list;
          this.adCount = res.data.size;
          resolve(res);
        }).catch(err => {
          reject(err);
        });
      });
    },
    toSearch() {
      this.currentPage = 1;
      this.getList();
    },
    resetSearchInfo() {
      Object.assign(this.$data.adSearchInfo, this.$options.data().adSearchInfo);
    },
    checkAll(value) {
      this.checkedCount = value ? this.adList.length : 0;
      this.adList.forEach(ad => {
        ad.selected = value;
      });
    },
    checkItem(value) {
      value ? this.checkedCount++ : this.checkedCount--;
    },
    clearAll() {
      if (this.checkedCount === 0) return;
      this.checkedCount = 0;
      this.checkedAll = false;
      this.adList.forEach(ad => {
        ad.selected = false;
      });
    },
    // 批量删除
    deleteMany() {
      if (this.checkedCount === 0) {
        this.$message({
          message: '请选择您要删除的广告',
          type: 'warning'
        });
        return false;
      }
      const selectedIdList = [];
      this.adList.filter(ad => {
        return ad.selected;
      }).map(ad => {
        selectedIdList.push(ad.id);
      });
      this.$confirm('此操作将永久删除该广告, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        new Promise((resolve, reject) => {
          delAndStart({ id: selectedIdList.join('/'), flag: '1', status: '', name: '', advertiseType: '', imagePc: '', imageApp: '', sort: '' }).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功'
            });
            this.clearAll();
            this.getList();
            resolve(res);
          }).catch(err => {
            reject(err);
          });
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    // 删除
    handleDelete(id) {
      this.$confirm('此操作将永久删除该广告, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        new Promise((resolve, reject) => {
          delAndStart({ id, flag: '1', status: '', name: '', advertiseType: '', imagePc: '', imageApp: '', sort: '' }).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功'
            });
            this.clearAll();
            this.getList();
            resolve(res);
          }).catch(err => {
            reject(err);
          });
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    changeStatus(ad) {
      new Promise((resolve, reject) => {
        delAndStart({ id: ad.id, flag: '', status: ad.status, name: '', advertiseType: '', imagePc: '', imageApp: '', sort: '' }).then(res => {
          resolve(res);
        }).catch(err => {
          reject(err);
        });
      });
    },
    // 分页
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.getList();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getList();
    }
  }
};
</script>
<style lang="scss" scoped>
@import '@/styles/shop-activity.scss';
.ad-list-wrapper{
  min-height: calc(100vh - 284px);
}
</style>
